package com.wgl.rocket.service;

import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author wgl
 * @version 1.0.0
 * @ClassName RocketService.java
 * @Description TODO
 * @createTime 2022年02月14日 14:11:00
 */
@Service
public class RocketService  {


    @Resource
    private DefaultMQProducer defaultMQProducer;

    public boolean sendMessage(String routingKey,Object message){


        String s = JSONObject.toJSONString(message);
        Message message1 = new Message("yygh", routingKey, s.getBytes(StandardCharsets.UTF_8));

        try {
             defaultMQProducer.send(message1,new SendCallback() {
                 //发送成功的回调函数
                 @Override
                 public void onSuccess(SendResult sendResult) {
                     System.out.println(sendResult);
                 }
                 //出现异常的回调函数
                 @Override
                 public void onException(Throwable throwable) {
                     System.out.println(throwable.getMessage());
                 }
             });
             return true;
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }
}
